package com.gui.hospital.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gui.entity.DateUtils;
import com.gui.hospital.mapper.NumberSourceMapper;
import com.gui.hospital.model.NumberSource;
import com.gui.hospital.service.NumberSourceService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

/**
 * @author 言叶
 * Date：2025/9/4
 */
@Service
@AllArgsConstructor
public class NumberSourceServiceImpl
        extends ServiceImpl<NumberSourceMapper, NumberSource>
        implements NumberSourceService {
    private final NumberSourceMapper numberSourceMapper;
    /*
     * 根据时间和医生id查询号源
     * @param dateTime
     * @param doctorId
     * @return
     */
    @Override
    public List<NumberSource> findByTimeAndDoctorId(Date dateTime, Integer doctorId) {
        QueryWrapper<NumberSource> queryWrapper = new QueryWrapper<>();
        //判断是否是当天号源
        Date now = new Date();
        String s1 = DateUtils.dateTime(dateTime);
        String s2 = DateUtils.dateTime(now);

        if (s1.equals(s2)) {
            //是当天，返回当天号源
            queryWrapper.lambda()
                    .eq(NumberSource::getDoctorId, doctorId)
                    .eq(NumberSource::getStatus, 0)
                    .ge(NumberSource::getPredictClinicTime, now)
                    .le(NumberSource::getPredictClinicTime, DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", s1 + " 23:59:59"));
        }
        else {
            //不是当天，返回当天号源
            queryWrapper.lambda()
                    .eq(NumberSource::getDoctorId, doctorId)
                    .eq(NumberSource::getStatus, 0)
                    .ge(NumberSource::getPredictClinicTime, dateTime)
                    .le(NumberSource::getPredictClinicTime, DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", s1 + " 23:59:59"));
        }
        return numberSourceMapper.selectList(queryWrapper);
    }
    /*
     * 更新号源状态
     * @param id
     * @param status
     * @return
     */
    @Override
    @GlobalTransactional
    public boolean updateStatusById(Long id, Long status) {
         int i = numberSourceMapper.updateStatusById(id, status);
         if(i == 0){
             throw new RuntimeException("号源已经被占用");
         }
         else {
             return true;
         }
    }
}
